package com.wendy.thirdpartyaccess.wechat;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wendy.thirdpartyaccess.SocialConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

import java.nio.charset.Charset;
import java.util.List;

/**
 * @author zhuwending
 */
@Slf4j
public class WechatImpl extends AbstractOAuth2ApiBinding implements Wechat {

    private ObjectMapper objectMapper = new ObjectMapper();

    public WechatImpl(String accessToken) {
        super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);
    }

    @Override
    protected List<HttpMessageConverter<?>> getMessageConverters() {
        List<HttpMessageConverter<?>> converters = super.getMessageConverters();
        converters.remove(0);
        converters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
        return converters;
    }

    @Override
    public WechatUserInfo getUserInfo(String openId) {
        String url = SocialConstants.URL_GET_USER_INFO + openId;
        String response = getRestTemplate().getForObject(url, String.class);
        String errcode = "errcode";
        if (StringUtils.contains(response, errcode)) {
            return null;
        }
        WechatUserInfo userInfo = null;
        try {
            userInfo = objectMapper.readValue(response, WechatUserInfo.class);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return userInfo;
    }
}
